package com.wefans.wefansapp.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.DrawerLayout.DrawerListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.wefans.wefansapp.R;
import com.wefans.wefansapp.common.tool.data.MFDataManager;
import com.wefans.wefansapp.common.tool.data.ResGetReply;
import com.wefans.wefansapp.common.tool.data.ResSetReply;
import com.wefans.wefansapp.common.tool.debug.MFDebug;
import com.wefans.wefansapp.common.tool.network.MFNetworkManager;
import com.wefans.wefansapp.common.tool.network.MFNetworkManager.IOnNetworkListener;
import com.wefans.wefansapp.common.tool.network.model.NetImage;
import com.wefans.wefansapp.common.tool.network.model.NetJsonData;
import com.wefans.wefansapp.common.tool.network.model.NetMessage;

/**
 * 댓글
 * 
 * @author kimhyeongbae
 */
public class ReplyActivity extends BaseActivity implements DrawerListener, IOnNetworkListener
{
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // final/static property
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    public static final String INTENT_EXTRA_TAG_REPLY_IDX = "INTENT_EXTRA_TAG_REPLY_IDX";
    
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // normal property
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    private DrawerLayout     m_DrawerLayout    = null;
    private FrameLayout      m_DrawerView      = null;
    
    private MFNetworkManager m_oNetworkManager = null;
    private MFDataManager    m_oDataManager    = null;
    
    private String           m_strIntentExtraReplyIdx = null;
    
    private ListView         m_lvReply         = null;
    
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // life-cycle method
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reply);
        
        MFDebug.d(">> onCreate()");
        
        initialize();
        installEvent();
    }

    @Override
    public void finish()
    {
        MFDebug.d(">> finish()");
        
        super.finish();
    }
    
    @Override
    protected void onPause()
    {
        MFDebug.d(">> onPause()");
        
        notifyDoClaseDrawerMenu();
        
        super.onPause();
    }

    @Override
    protected void notifyDoClaseDrawerMenu()
    {
        MFDebug.d(">> notifyDoClaseDrawerMenu()");
        
        super.notifyDoClaseDrawerMenu();
        
        if( m_DrawerLayout == null ) {
            MFDebug.e(new Exception("There are NO Drawer-Layout"));
            return;
        }
        
        if( m_DrawerView == null ) {
            MFDebug.e(new Exception("There are NO Drawer-View"));
            return;
        }
        
        m_DrawerLayout.closeDrawer(m_DrawerView);
        m_sdQuickMenu.close();
    }
    
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // normal method
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    private void initialize()
    {
        MFDebug.d(">> initialize()");
        
        m_strIntentExtraReplyIdx = getIntent().getStringExtra(INTENT_EXTRA_TAG_REPLY_IDX);
        MFDebug.d("++ m_strIntentExtraReplyIdx : " + m_strIntentExtraReplyIdx);
        
        m_oNetworkManager = MFNetworkManager.getInstance(this);
        m_oDataManager    = MFDataManager.getInstance(this);
        
        //[Step 1] Contents layout adding
        FrameLayout containerContents = (FrameLayout) findViewById(R.id.FL_REPLY_CONTAINER);
        addContentsLayout(containerContents, R.layout.layout_reply_contents);
        addQuickMenuLayout(containerContents);
        
        //[Step 2] Drawer menu adding
        m_DrawerView = (FrameLayout) findViewById(R.id.FL_REPLY_DRAWER_LAYOUT);
        addDrawerLayout(m_DrawerView);
        
        //[Step 3] set drawer layout (root)
        m_DrawerLayout = (DrawerLayout) findViewById(R.id.DL_REPLY_NAVIGATION_LAYOUT);
        
        //[Step 4] request server data
        {
            requestReplyList();
        }
        
        m_lvReply = (ListView) findViewById(R.id.LV_REAPLY_BODY_CONTENTS);
        
        //[TEST]
        {
            List<String> listReply = new ArrayList<String>();
            listReply.add("작성자에 의해 삭제된 글입니다.");
            listReply.add("관리자에 의해 삭제된 글입니다.");
            CAdapter adapter = new CAdapter(this, -1, -1, listReply);
            m_lvReply.setAdapter(adapter);
        }
    }
    
    private void installEvent()	
    {
        MFDebug.d(">> installEvent()");
        
        ((Button) findViewById(R.id.BT_REPLY_BODY_REGIST_BTN)).setOnClickListener(this);
        ((ImageButton) findViewById(R.id.IB_REPLY_BODY_REPORT)).setOnClickListener(this);
        ((ImageButton) findViewById(R.id.IB_REPLY_BODY_DELETE)).setOnClickListener(this);
    }
    
    /**
     * 댓글리스트를 가져온다.
     * 
     */
    private void requestReplyList()
    {
        MFDebug.d(">> requestReplyList()");
        
        m_oNetworkManager.requestReplayList(this, "1", m_strIntentExtraReplyIdx, "0", "1", "idx");
    }
    
    /**
     * 댓글 등록
     * 
     */
    private void requestReplyRegist()
    {
        MFDebug.d(">> requestReplyRegist");
        
        EditText etReply = (EditText) findViewById(R.id.ET_REPLY_BODY_INPUT);
        
        m_oNetworkManager.requestReplayRegist(this, "1", m_strIntentExtraReplyIdx, "0", etReply.getText().toString());
    }
    
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // network interface
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    @Override
    public void onNetMessage(int resultCode, NetMessage message)
    {
        MFDebug.d(">> onNetMessage()");
        MFDebug.d("++ resultCode : " + resultCode);
        MFDebug.d("++ message : " + message);
        
        try {
            //서버 여동 데이터
            if( message instanceof NetJsonData ) {
                long magicNum = ((NetJsonData) message).getMagicNum();
                String json = ((NetJsonData) message).getResponseJson();
                
                if( json == null ) {
                    throw new Exception("There are NO json data");
                }
                
                Gson gson = new Gson();
                
                if( magicNum == MFNetworkManager.REQUEST_REPLY_LIST ) {
                    ResGetReply replyList = (ResGetReply) gson.fromJson(json, ResGetReply.class);
                    
                    if( replyList == null ) {
                        throw new Exception("Json parsing error");
                    }
                }
                else if( magicNum == MFNetworkManager.REQUEST_REPLY_REGIST ) {
                    ResSetReply replySet = (ResSetReply) gson.fromJson(json, ResSetReply.class);
                    
                    if( replySet == null ) {
                        throw new Exception("Json parsing error");
                    }
                }
                
            }
            //이미지 데이터
            else if( message instanceof NetImage ) {
                long   magicNum = ((NetImage)message).getMagicNum();
                String url      = ((NetImage)message).getURL();
                byte[] buffer   = ((NetImage)message).getResponseBinary();
                
                if( buffer == null ) {
                    throw new Exception("There are NO image data");
                }
            }
            else {
                //ignore...
            }
        } catch(Exception e) {
            MFDebug.e(e);
        }
    }
    
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // interface method
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    @Override
    public void onClick(View v)
    {
        MFDebug.d(">> onClick()");
        
        switch( v.getId() ) {
            case R.id.BT_REPLY_BODY_REGIST_BTN :
                requestReplyRegist();
                break;
            case R.id.IB_REPLY_BODY_REPORT :
                break;
            case R.id.IB_REPLY_BODY_DELETE :
                break;
            default :
                break;
        }
        
        super.onClick(v);
    }

    @Override
    public void onDrawerClosed(View drawerView)
    {
        MFDebug.d(">> onDrawerClosed()");
        MFDebug.d("++ drawerView : " + drawerView);
    }

    @Override
    public void onDrawerOpened(View drawerView)
    {
        MFDebug.d(">> onDrawerOpened()");
        MFDebug.d("++ drawerView : " + drawerView);
    }

    @Override
    public void onDrawerSlide(View drawerView, float slideOffset)
    {
        MFDebug.d(">> onDrawerSlide()");
        MFDebug.d("++ drawerView : " + drawerView);
        MFDebug.d("++ slideOffset : " + slideOffset);
    }

    @Override
    public void onDrawerStateChanged(int newState)
    {
        MFDebug.d(">> onDrawerStateChanged()");
        MFDebug.d("++ newState : " + newState);
        
        String state = null;
        switch (newState) {
        case DrawerLayout.STATE_IDLE:
            state = "STATE_IDLE";
            break;
        case DrawerLayout.STATE_DRAGGING:
            state = "STATE_DRAGGING";
            break;
        case DrawerLayout.STATE_SETTLING:
            state = "STATE_SETTLING";
            break;
        default:
            state = "unknown!";
        }
        MFDebug.d("++ state : " + state);
    }
    
    /******************************************************************************************************************
     * 메인(투표하기) 리스트 어뎁터클래스
     * 
     * @author kimhyeongbae
     *
     ******************************************************************************************************************/
    class CAdapter extends ArrayAdapter<String>
    {
        private LayoutInflater           m_oInflater           = null;
        private List<String>             m_listReply         = null;

        public CAdapter(Context context, int resource, int textViewResourceId, List<String> objects)
        {
            super(context, resource, textViewResourceId, objects);
            
            m_listReply = objects;
            
            m_oInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            if( convertView == null ) {
                convertView = m_oInflater.inflate(R.layout.list_item_reply_list, null);
            }
            
            final String item = m_listReply.get(position);
            
            TextView  tvReply   = (TextView)  convertView.findViewById(R.id.TV_REPLY_BODY_LIST_ITEM);
            tvReply.setText(item);
            
            return convertView;
        }
    };
}
